{% extends "base.html" %}

{% block title %}写作 - 云水禅心居{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="../static/css/simplemde.min.css">
<link rel="stylesheet" href="../static/css/font-awesome.min.css">
<style>
    .editor-container {
        max-width: 1200px;
        margin: 2rem auto;
        padding: 0 1rem;
    }
    /* 删除原来的 .title-input 样式 */
    
    /* 添加新的brutalist风格输入框样式 */
    .brutalist-container {
      position: relative;
      width: 100%;
      font-family: monospace;
      margin-bottom: 1.5rem;
    }

    .brutalist-input {
      width: 100%;
      padding: 15px;
      font-size: 18px;
      font-weight: bold;
      color: #000;
      background-color: #fff;
      border: 4px solid #000;
      position: relative;
      overflow: hidden;
      border-radius: 0;
      outline: none;
      transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
      box-shadow: 5px 5px 0 #000, 10px 10px 0 #4a90e2;
    }

    @keyframes glitch {
      0% {
        transform: translate(0);
      }
      20% {
        transform: translate(-2px, 2px);
      }
      40% {
        transform: translate(-2px, -2px);
      }
      60% {
        transform: translate(2px, 2px);
      }
      80% {
        transform: translate(2px, -2px);
      }
      100% {
        transform: translate(0);
      }
    }

    .brutalist-input:focus {
      animation: focus-pulse 4s cubic-bezier(0.25, 0.8, 0.25, 1) infinite,
        glitch 0.3s cubic-bezier(0.25, 0.8, 0.25, 1) infinite;
    }

    .brutalist-input:focus::after {
      content: "";
      position: absolute;
      top: -2px;
      left: -2px;
      right: -2px;
      bottom: -2px;
      background: white;
      z-index: -1;
    }

    .brutalist-input:focus::before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: black;
      z-index: -2;
      clip-path: inset(0 100% 0 0);
      animation: glitch-slice 4s steps(2, end) infinite;
    }

    @keyframes glitch-slice {
      0% {
        clip-path: inset(0 100% 0 0);
      }
      10% {
        clip-path: inset(0 5% 0 0);
      }
      20% {
        clip-path: inset(0 80% 0 0);
      }
      30% {
        clip-path: inset(0 10% 0 0);
      }
      40% {
        clip-path: inset(0 50% 0 0);
      }
      50% {
        clip-path: inset(0 30% 0 0);
      }
      60% {
        clip-path: inset(0 70% 0 0);
      }
      70% {
        clip-path: inset(0 15% 0 0);
      }
      80% {
        clip-path: inset(0 90% 0 0);
      }
      90% {
        clip-path: inset(0 5% 0 0);
      }
      100% {
        clip-path: inset(0 100% 0 0);
      }
    }

    .brutalist-label {
      position: absolute;
      left: -3px;
      top: -35px;
      font-size: 14px;
      font-weight: bold;
      color: #fff;
      background-color: #000;
      padding: 5px 10px;
      transform: rotate(-1deg);
      z-index: 1;
      transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    }

    .brutalist-input:focus + .brutalist-label {
      transform: rotate(0deg) scale(1.05);
      background-color: #4a90e2;
    }

    .smooth-type {
      position: relative;
      overflow: hidden;
    }

    .smooth-type::before {
      content: "";
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background: linear-gradient(90deg, #fff 0%, rgba(255, 255, 255, 0) 100%);
      z-index: 1;
      opacity: 0;
      transition: opacity 0.3s ease;
    }

    .smooth-type:focus::before {
      opacity: 1;
      animation: type-gradient 2s linear infinite;
    }

    @keyframes type-gradient {
      0% {
        background-position: 300px 0;
      }
      100% {
        background-position: 0 0;
      }
    }

    .brutalist-input::placeholder {
      color: #888;
      transition: color 0.3s ease;
    }

    .brutalist-input:focus::placeholder {
      color: transparent;
    }

    .brutalist-input:focus {
      animation: focus-pulse 4s cubic-bezier(0.25, 0.8, 0.25, 1) infinite;
    }

    @keyframes focus-pulse {
      0%,
      100% {
        border-color: #000;
      }
      50% {
        border-color: #4a90e2;
      }
    }
    .tags-input {
        background-color: #383838;
        border: 1ex solid none;
        border-top-width: 1.7em;
        margin: 0 0 1rem 0;
        padding: 0;
        color: #383838;
        word-wrap: break-word;
        outline: 7px solid #383838;
        height: 30px;
        font-size: 17px;
        text-align: center;
        transition: all 1s;
        width: 100%;
        font-weight: bold;
        font-family: 'Courier New', Courier, monospace;
    }
    .tags-input:hover {
        border-top-width: 0.2em;
        background-color: #f1e8e8;
        color: #000;
    }
    .tags-input:focus {
        border-top-width: 0.2em;
        background-color: #f1e8e8;
        color: #000;
    }
    .help-text {
        color: #666;
        font-size: 0.9rem;
        margin-top: 0.25rem;
    }
    .editor-toolbar {
        border: 1px solid #ddd;
        border-bottom: none;
        border-radius: 4px 4px 0 0;
    }
    .CodeMirror {
        border: 1px solid #ddd;
        border-radius: 0 0 4px 4px;
    }
    .editor-preview {
        border: 1px solid #ddd;
        border-radius: 0 0 4px 4px;
    }
    .editor-preview-side {
        border: 1px solid #ddd;
        border-radius: 0 0 4px 4px;
    }
    .editor-statusbar {
        border: 1px solid #ddd;
        border-top: none;
        border-radius: 0 0 4px 4px;
    }
    .action-buttons {
        display: flex;
        gap: 1rem;
        margin-top: 1rem;
    }
    .cover-image-section {
        margin-bottom: 1.5rem;
        border: 1px dashed #ddd;
        padding: 1.5rem;
        border-radius: 4px;
        background: #f9f9f9;
    }
    .cover-image-title {
        font-size: 1.1rem;
        margin-bottom: 1rem;
        font-weight: 500;
    }
    .cover-image-preview {
        width: 100%;
        height: 200px;
        margin-bottom: 1rem;
        border-radius: 4px;
        background-color: #f0f0f0;
        background-size: cover;
        background-position: center;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #aaa;
        font-size: 0.9rem;
    }
    .cover-image-upload {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    .file-input-wrapper {
        position: relative;
        overflow: hidden;
        display: inline-block;
    }
    .file-input-wrapper input[type=file] {
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
    .btn-upload {
        background-color: #007bff;
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 4px;
        cursor: pointer;
    }
    .btn-upload:hover {
        background-color: #0069d9;
    }
    .btn-compress {
        background-color: #28a745;
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 4px;
        cursor: pointer;
        text-decoration: none;
        display: inline-block;
        font-size: 0.9rem;
        text-align: center;
    }
    .btn-compress:hover {
        background-color: #218838;
        text-decoration: none;
        color: white;
    }
    .file-name {
        color: #666;
        font-size: 0.9rem;
    }
    #markdown-editor {
        display: none; /* 初始隐藏编辑区域，等待编辑器初始化 */
        min-height: 400px;
    }
    #editor-loading {
        background-color: #f9f9f9;
        border: 1px solid #ddd;
        border-radius: 4px;
        text-align: center;
        padding: 1rem;
        margin-bottom: 1rem;
    }
    
    /* 现代按钮样式 */
    .animated-button {
      position: relative;
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 16px 36px;
      border: 4px solid;
      border-color: transparent;
      font-size: 16px;
      background-color: inherit;
      border-radius: 100px;
      font-weight: 600;
      color: greenyellow;
      box-shadow: 0 0 0 2px greenyellow;
      cursor: pointer;
      overflow: hidden;
      transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);
    }

    .animated-button svg {
      position: absolute;
      width: 24px;
      fill: greenyellow;
      z-index: 9;
      transition: all 0.8s cubic-bezier(0.23, 1, 0.32, 1);
    }

    .animated-button .arr-1 {
      right: 16px;
    }

    .animated-button .arr-2 {
      left: -25%;
    }

    .animated-button .circle {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 20px;
      height: 20px;
      background-color: greenyellow;
      border-radius: 50%;
      opacity: 0;
      transition: all 0.8s cubic-bezier(0.23, 1, 0.32, 1);
    }

    .animated-button .text {
      position: relative;
      z-index: 1;
      transform: translateX(-12px);
      transition: all 0.8s cubic-bezier(0.23, 1, 0.32, 1);
    }

    .animated-button:hover {
      box-shadow: 0 0 0 12px transparent;
      color: #212121;
      border-radius: 12px;
    }

    .animated-button:hover .arr-1 {
      right: -25%;
    }

    .animated-button:hover .arr-2 {
      left: 16px;
    }

    .animated-button:hover .text {
      transform: translateX(12px);
    }

    .animated-button:hover svg {
      fill: #212121;
    }

    .animated-button:active {
      scale: 0.95;
      box-shadow: 0 0 0 4px greenyellow;
    }

    .animated-button:hover .circle {
      width: 220px;
      height: 220px;
      opacity: 1;
    }
    
    /* 自定义草稿按钮样式 */
    .btn-draft {
      color: #6c757d;
      box-shadow: 0 0 0 2px #6c757d;
    }
    
    .btn-draft svg {
      fill: #6c757d;
    }
    
    .btn-draft .circle {
      background-color: #6c757d;
    }
    
    .btn-draft:active {
      box-shadow: 0 0 0 4px #6c757d;
    }

    /* 添加cssbuttons-io样式 */
    .cssbuttons-io-button {
      background: #007bff;
      color: white;
      font-family: inherit;
      padding: 0.35em;
      padding-left: 1.2em;
      font-size: 15px;
      font-weight: 500;
      border-radius: 0.9em;
      border: none;
      letter-spacing: 0.05em;
      display: flex;
      align-items: center;
      box-shadow: inset 0 0 1.6em -0.6em #0056b3;
      overflow: hidden;
      position: relative;
      height: 2.8em;
      padding-right: 3.3em;
      cursor: pointer;
    }
    
    .cssbuttons-io-button .icon {
      background: white;
      margin-left: 1em;
      position: absolute;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 2.2em;
      width: 2.2em;
      border-radius: 0.7em;
      box-shadow: 0.1em 0.1em 0.6em 0.2em #0056b3;
      right: 0.3em;
      transition: all 0.3s;
    }
    
    .cssbuttons-io-button:hover .icon {
      width: calc(100% - 0.6em);
    }
    
    .cssbuttons-io-button .icon svg {
      width: 1.1em;
      transition: transform 0.3s;
      color: #0056b3;
    }
    
    .cssbuttons-io-button:hover .icon svg {
      transform: translateX(0.1em);
    }
    
    .cssbuttons-io-button:active .icon {
      transform: scale(0.95);
    }
    
    /* 压缩按钮的颜色变量 */
    .cssbuttons-io-button.btn-compress-new {
      background: #28a745;
      box-shadow: inset 0 0 1.6em -0.6em #1f8a37;
    }
    
    .cssbuttons-io-button.btn-compress-new .icon {
      box-shadow: 0.1em 0.1em 0.6em 0.2em #1f8a37;
    }
    
    .cssbuttons-io-button.btn-compress-new .icon svg {
      color: #1f8a37;
    }
    
    /* 标签选择区域样式 */
    .tags-selection {
        margin-bottom: 1.5rem;
        border: 1px dashed #ddd;
        padding: 1.5rem;
        border-radius: 4px;
        background: #f9f9f9;
    }
    
    .tags-selection-title {
        font-size: 1.1rem;
        margin-bottom: 1rem;
        font-weight: 500;
    }
    
    .tags-selection-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 1rem;
    }
    
    .tag-checkbox {
        display: none;
    }
    
    .tag-label {
        display: inline-flex;
        align-items: center;
        padding: 6px 12px;
        background-color: #fff;
        border: 2px solid #e0e0e0;
        border-radius: 30px;
        cursor: pointer;
        transition: all 0.3s;
        user-select: none;
    }
    
    .tag-label:hover {
        border-color: #4a90e2;
        transform: translateY(-3px);
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    
    .tag-checkbox:checked + .tag-label {
        background-color: #4a90e2;
        color: white;
        border-color: #4a90e2;
    }
    
    .tag-checkbox:checked + .tag-label::before {
        content: "✓";
        margin-right: 5px;
        font-weight: bold;
    }
    
    .loading-tags {
        color: #666;
        font-style: italic;
    }
    
    /* 标签复选框新样式 - From Uiverse.io by SelfMadeSystem */
    .container {
      cursor: pointer;
      margin: 8px;
      display: inline-flex;
      align-items: center;
    }

    .container input {
      display: none;
    }

    .container svg {
      overflow: visible;
      margin-right: 8px;
    }

    .path {
      fill: none;
      stroke: #4a90e2;
      stroke-width: 6;
      stroke-linecap: round;
      stroke-linejoin: round;
      transition: stroke-dasharray 0.5s ease, stroke-dashoffset 0.5s ease;
      stroke-dasharray: 241 9999999;
      stroke-dashoffset: 0;
    }

    .container input:checked ~ svg .path {
      stroke-dasharray: 70.5096664428711 9999999;
      stroke-dashoffset: -262.2723388671875;
    }
    
    .container .tag-name {
      font-size: 14px;
      transition: all 0.3s;
      color: #555;
    }
    
    .container:hover .tag-name {
      color: #4a90e2;
      transform: translateY(-2px);
    }
    
    .container input:checked ~ .tag-name {
      color: #4a90e2;
      font-weight: bold;
    }
    
    .tag-label-text {
      background-color: #f0f4f8;
      padding: 5px 10px;
      border-radius: 15px;
      border: 1px solid #e0e0e0;
      transition: all 0.3s;
    }
    
    .container:hover .tag-label-text {
      background-color: #e6f2ff;
      border-color: #4a90e2;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
    
    .container input:checked ~ .tag-label-text {
      background-color: #4a90e2;
      color: white;
      border-color: #4a90e2;
    }
</style>
<script src="..\static\js\simplemde.min.js" defer></script>
{% endblock %}

{% block content %}
<div class="editor-container">
    <form method="POST" id="post-form" enctype="multipart/form-data">
        {{ form.hidden_tag() }}
        <div class="form-group">
            <div class="brutalist-container">
                {{ form.title(class="brutalist-input smooth-type", placeholder="输入文章标题") }}
                <label class="brutalist-label">文章标题</label>
            </div>
            {% for error in form.title.errors %}
                <span class="error-message">{{ error }}</span>
            {% endfor %}
        </div>
        
        <div class="cover-image-section">
            <h3 class="cover-image-title">文章封面</h3>
            <div class="cover-image-preview" id="cover-preview">
                <span>未选择封面图片，将使用默认封面</span>
            </div>
            <div class="cover-image-upload">
                <div class="file-input-wrapper">
                    <button class="cssbuttons-io-button">
                        选择图片
                        <div class="icon">
                            <svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path d="M0 0h24v24H0z" fill="none"></path>
                                <path d="M16.172 11l-5.364-5.364 1.414-1.414L20 12l-7.778 7.778-1.414-1.414L16.172 13H4v-2z" fill="currentColor"></path>
                            </svg>
                        </div>
                    </button>
                    {{ form.cover_image(id="cover-image-input", onchange="previewImage(this)") }}
                </div>
                <a href="https://docsmall.com/image-compress" target="_blank" class="cssbuttons-io-button btn-compress-new">
                    压缩图片
                    <div class="icon">
                        <svg height="24" width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path d="M0 0h24v24H0z" fill="none"></path>
                            <path d="M16.172 11l-5.364-5.364 1.414-1.414L20 12l-7.778 7.778-1.414-1.414L16.172 13H4v-2z" fill="currentColor"></path>
                        </svg>
                    </div>
                </a>
                <span class="file-name" id="file-name">未选择任何文件</span>
            </div>
            {% for error in form.cover_image.errors %}
                <span class="error-message">{{ error }}</span>
            {% endfor %}
        </div>
        
        <div class="form-group">
            {{ form.tags(class="tags-input", placeholder="输入标签，用逗号分隔") }}
            <div class="help-text">多个标签请用逗号分隔，如：技术,生活,随笔</div>
            {% for error in form.tags.errors %}
                <span class="error-message">{{ error }}</span>
            {% endfor %}
        </div>
        
        <!-- 标签选择区域 -->
        <div class="tags-selection">
            <h3 class="tags-selection-title">选择已有标签</h3>
            <div class="tags-selection-container" id="tagsContainer">
                <!-- 标签选择区域将通过JavaScript动态填充 -->
                <div class="loading-tags">正在加载标签...</div>
            </div>
        </div>
        
        <div class="form-group">
            {{ form.content(id="markdown-editor") }}
            {% for error in form.content.errors %}
                <span class="error-message">{{ error }}</span>
            {% endfor %}
        </div>
        <div class="action-buttons">
            <!-- 保存草稿按钮 -->
            <button type="button" class="animated-button btn-draft" onclick="saveAsDraft()">
                <svg viewBox="0 0 24 24" class="arr-2" xmlns="http://www.w3.org/2000/svg">
                    <path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z"></path>
                </svg>
                <span class="text">保存草稿</span>
                <span class="circle"></span>
                <svg viewBox="0 0 24 24" class="arr-1" xmlns="http://www.w3.org/2000/svg">
                    <path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z"></path>
                </svg>
            </button>
            
            <!-- 发布文章按钮 -->
            <button type="button" class="animated-button" onclick="publishPost()">
                <svg viewBox="0 0 24 24" class="arr-2" xmlns="http://www.w3.org/2000/svg">
                    <path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z"></path>
                </svg>
                <span class="text">发布文章</span>
                <span class="circle"></span>
                <svg viewBox="0 0 24 24" class="arr-1" xmlns="http://www.w3.org/2000/svg">
                    <path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z"></path>
                </svg>
            </button>
        </div>
    </form>
</div>
{% endblock %}

{% block scripts %}
<script>
    /* 检查是否需要清除草稿 */
    {{ clear_draft_js|safe }}

    /* 检查是否清除了草稿 */
    var isCleared = {{ 'true' if clear_draft_js else 'false' }};
    var simplemde = null;

    /* 延迟加载和初始化编辑器 */
    function initEditor() {
        // 如果编辑器已初始化，直接返回
        if (simplemde) return;
        
        // 显示一个小型加载指示器
        var editorElement = document.getElementById("markdown-editor");
        var loadingIndicator = document.createElement("div");
        loadingIndicator.id = "editor-loading";
        loadingIndicator.innerHTML = "编辑器加载中...";
        loadingIndicator.style.padding = "1rem";
        loadingIndicator.style.color = "#666";
        editorElement.parentNode.insertBefore(loadingIndicator, editorElement);

        // 自定义按钮提示
        var customToolbarTooltips = {
            "bold": "粗体 (Ctrl+B)",
            "italic": "斜体 (Ctrl+I)",
            "heading": "标题 (Ctrl+H)",
            "quote": "引用 (Ctrl+Q)",
            "unordered-list": "无序列表 (Ctrl+U)",
            "ordered-list": "有序列表 (Ctrl+O)",
            "link": "添加链接 (Ctrl+L)",
            "image": "添加图片 (Ctrl+Alt+I)",
            "code": "代码 (Ctrl+Alt+C)",
            "table": "插入表格",
            "preview": "预览 (Ctrl+P)",
            "side-by-side": "分屏预览 (F9)",
            "fullscreen": "全屏 (F11)",
            "guide": "Markdown 指南",
            "horizontal-rule": "水平分割线",
            "strikethrough": "删除线",
            "clean-block": "清除格式",
            "undo": "撤销 (Ctrl+Z)",
            "redo": "重做 (Ctrl+Y)"
        };

        // 自定义工具栏
        var customToolbar = [
            {
                name: "bold",
                action: SimpleMDE.toggleBold,
                className: "fa fa-bold",
                title: "粗体 (Ctrl+B)",
            },
            {
                name: "italic",
                action: SimpleMDE.toggleItalic,
                className: "fa fa-italic",
                title: "斜体 (Ctrl+I)",
            },
            {
                name: "heading",
                action: SimpleMDE.toggleHeadingSmaller,
                className: "fa fa-header",
                title: "标题 (Ctrl+H)",
            },
            "|",
            {
                name: "quote",
                action: SimpleMDE.toggleBlockquote,
                className: "fa fa-quote-left",
                title: "引用 (Ctrl+Q)",
            },
            {
                name: "unordered-list",
                action: SimpleMDE.toggleUnorderedList,
                className: "fa fa-list-ul",
                title: "无序列表 (Ctrl+U)",
            },
            {
                name: "ordered-list",
                action: SimpleMDE.toggleOrderedList,
                className: "fa fa-list-ol",
                title: "有序列表 (Ctrl+O)",
            },
            "|",
            {
                name: "link",
                action: SimpleMDE.drawLink,
                className: "fa fa-link",
                title: "添加链接 (Ctrl+L)",
            },
            {
                name: "image",
                action: SimpleMDE.drawImage,
                className: "fa fa-picture-o",
                title: "添加图片 (Ctrl+Alt+I)",
            },
            {
                name: "code",
                action: SimpleMDE.toggleCodeBlock,
                className: "fa fa-code",
                title: "代码 (Ctrl+Alt+C)",
            },
            {
                name: "table",
                action: SimpleMDE.drawTable,
                className: "fa fa-table",
                title: "插入表格",
            },
            "|",
            {
                name: "preview",
                action: SimpleMDE.togglePreview,
                className: "fa fa-eye no-disable",
                title: "预览 (Ctrl+P)",
            },
            {
                name: "side-by-side",
                action: SimpleMDE.toggleSideBySide,
                className: "fa fa-columns no-disable no-mobile",
                title: "分屏预览 (F9)",
            },
            {
                name: "fullscreen",
                action: SimpleMDE.toggleFullScreen,
                className: "fa fa-arrows-alt no-disable no-mobile",
                title: "全屏 (F11)",
            },
            "|",
            {
                name: "guide",
                action: "https://www.markdownguide.org/basic-syntax/",
                className: "fa fa-question-circle",
                title: "Markdown 指南",
            },
            "|",
            {
                name: "horizontal-rule",
                action: SimpleMDE.drawHorizontalRule,
                className: "fa fa-minus",
                title: "水平分割线",
            },
            {
                name: "strikethrough",
                action: SimpleMDE.toggleStrikethrough,
                className: "fa fa-strikethrough",
                title: "删除线",
            },
            "|",
            {
                name: "clean-block",
                action: SimpleMDE.cleanBlock,
                className: "fa fa-eraser",
                title: "清除格式",
            },
            {
                name: "undo",
                action: SimpleMDE.undo,
                className: "fa fa-undo",
                title: "撤销 (Ctrl+Z)",
            },
            {
                name: "redo",
                action: SimpleMDE.redo,
                className: "fa fa-repeat",
                title: "重做 (Ctrl+Y)",
            },
        ];

        // 如果草稿已被清除，不从本地存储加载初始内容
        var initialContent = isCleared ? '' : (localStorage.getItem('draft_content') || '');

        // 移除加载指示器
        loadingIndicator.remove();

        // 初始化编辑器
        simplemde = new SimpleMDE({
            element: document.getElementById("markdown-editor"),
            spellChecker: false,
            autosave: {
                enabled: !isCleared, // 如果草稿已被清除，禁用自动保存
                uniqueId: "post_editor",
                delay: 1000,
                text: "自动保存中...",
                savingText: "已保存",
                messageClass: "editor-statusbar",
            },
            placeholder: "开始写作...",
            toolbar: customToolbar,
            status: ["lines", "words", "cursor"],
            renderingConfig: {
                singleLineBreaks: true,
                codeSyntaxHighlighting: true,
            },
            initialValue: initialContent
        });
    }

    // 预览封面图片
    function previewImage(input) {
        var preview = document.getElementById('cover-preview');
        var fileName = document.getElementById('file-name');
        
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function(e) {
                // 创建图片元素
                var img = document.createElement('img');
                img.src = e.target.result;
                img.style.width = '100%';
                img.style.height = '100%';
                img.style.objectFit = 'cover';
                
                // 清空预览区域并添加图片
                preview.innerHTML = '';
                preview.appendChild(img);
                
                // 显示文件名
                fileName.textContent = input.files[0].name;
            }
            
            reader.readAsDataURL(input.files[0]);
        } else {
            preview.innerHTML = '<span>未选择封面图片，将使用默认封面</span>';
            fileName.textContent = '未选择任何文件';
        }
    }

    // 发布文章函数
    function publishPost() {
        // 确保编辑器已初始化
        if (!simplemde) {
            alert('编辑器尚未加载完成，请稍候再试');
            return;
        }
        
        var content = simplemde.value();
        var title = document.querySelector('.brutalist-input').value;
        
        // 验证内容
        if (!title.trim()) {
            alert('请输入文章标题');
            return;
        }
        
        if (!content.trim()) {
            alert('请输入文章内容');
            return;
        }
        
        // 更新表单内容
        document.getElementById('markdown-editor').value = content;
        
        // 提交表单
        document.getElementById('post-form').submit();
    }

    function saveAsDraft() {
        // 确保编辑器已初始化
        if (!simplemde) {
            alert('编辑器尚未加载完成，请稍候再试');
            return;
        }
        
        // 保存草稿功能
        localStorage.setItem('draft_title', document.querySelector('.brutalist-input').value);
        localStorage.setItem('draft_content', simplemde.value());
        localStorage.setItem('draft_tags', document.querySelector('.tags-input').value);
        alert('草稿已保存！');
    }

    // 加载标签列表并创建选择项
    function loadTags() {
        // 获取标签容器
        const tagsContainer = document.getElementById('tagsContainer');
        
        // 发起AJAX请求获取所有标签
        fetch('/get_all_tags')
            .then(response => response.json())
            .then(tags => {
                // 清空加载提示
                tagsContainer.innerHTML = '';
                
                // 如果没有标签，显示提示
                if (tags.length === 0) {
                    tagsContainer.innerHTML = '<div class="no-tags">暂无标签，请直接在上方输入框中创建</div>';
                    return;
                }
                
                // 为每个标签创建新的复选框
                tags.forEach(tag => {
                    // 创建唯一ID
                    const id = `tag-${tag.id}`;
                    
                    // 创建标签容器
                    const label = document.createElement('label');
                    label.className = 'container';
                    
                    // 创建复选框
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.id = id;
                    checkbox.value = tag.name;
                    
                    // 创建SVG图标
                    const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
                    svg.setAttribute("viewBox", "0 0 64 64");
                    svg.setAttribute("height", "2em");
                    svg.setAttribute("width", "2em");
                    
                    const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
                    path.setAttribute("d", "M 0 16 V 56 A 8 8 90 0 0 8 64 H 56 A 8 8 90 0 0 64 56 V 8 A 8 8 90 0 0 56 0 H 8 A 8 8 90 0 0 0 8 V 16 L 32 48 L 64 16 V 8 A 8 8 90 0 0 56 0 H 8 A 8 8 90 0 0 0 8 V 56 A 8 8 90 0 0 8 64 H 56 A 8 8 90 0 0 64 56 V 16");
                    path.setAttribute("pathLength", "575.0541381835938");
                    path.setAttribute("class", "path");
                    svg.appendChild(path);
                    
                    // 创建标签文本容器
                    const tagName = document.createElement('span');
                    tagName.className = 'tag-name';
                    tagName.textContent = tag.name;
                    
                    // 将所有元素添加到标签容器
                    label.appendChild(checkbox);
                    label.appendChild(svg);
                    label.appendChild(tagName);
                    
                    // 添加事件监听器，处理选择标签
                    checkbox.addEventListener('change', function() {
                        updateTagsInput();
                    });
                    
                    // 将标签添加到容器
                    tagsContainer.appendChild(label);
                });
            })
            .catch(error => {
                console.error('获取标签失败:', error);
                tagsContainer.innerHTML = '<div class="error-message">加载标签失败，请刷新页面重试</div>';
            });
    }
    
    // 更新标签输入框内容
    function updateTagsInput() {
        const tagsInput = document.querySelector('.tags-input');
        const checkboxes = document.querySelectorAll('.container input');
        const checkedBoxes = document.querySelectorAll('.container input:checked');
        
        // 获取所有复选框对应的标签
        const allCheckboxTags = Array.from(checkboxes).map(cb => cb.value);
        
        // 获取用户手动输入的标签（排除复选框已有的标签）
        let manualTags = tagsInput.value.split(',')
            .map(tag => tag.trim())
            .filter(tag => tag !== '' && !allCheckboxTags.includes(tag));
        
        // 获取选中的标签
        const selectedTags = Array.from(checkedBoxes).map(cb => cb.value);
        
        // 合并手动输入的标签和选中的标签
        const allTags = [...manualTags, ...selectedTags];
        
        // 更新标签输入框
        tagsInput.value = allTags.join(', ');
    }

    // 监听标签输入框的变化
    function setupTagsInputListener() {
        const tagsInput = document.querySelector('.tags-input');
        
        // 监听输入事件，同步更新复选框状态
        tagsInput.addEventListener('input', function() {
            const inputTags = this.value.split(',').map(tag => tag.trim()).filter(tag => tag !== '');
            
            // 获取所有复选框
            const checkboxes = document.querySelectorAll('.container input');
            
            // 更新复选框状态
            checkboxes.forEach(checkbox => {
                // 如果标签在输入框中存在，则选中对应的复选框
                checkbox.checked = inputTags.includes(checkbox.value);
            });
        });
    }

    // 在页面加载完成后显示编辑区域内容并加载草稿
    window.onload = function() {
        // 显示编辑区域的内容
        document.getElementById('markdown-editor').style.display = 'block';
        
        // 如果是从其他页面导航过来，页面已经完全加载，隐藏全局加载动画
        var loader = document.getElementById('pageLoader');
        if (loader) {
            loader.style.opacity = '0';
            setTimeout(function() {
                loader.style.display = 'none';
                // 加载编辑器
                initEditor();
            }, 300);
        } else {
            // 直接加载编辑器
            initEditor();
        }
        
        // 加载标签选择区域
        loadTags();
        
        // 设置标签输入框的监听器
        setupTagsInputListener();
        
        // 如果草稿已被清除，不加载草稿
        if (isCleared) return;
        
        const draftTitle = localStorage.getItem('draft_title');
        const draftTags = localStorage.getItem('draft_tags');
        
        if (draftTitle) document.querySelector('.brutalist-input').value = draftTitle;
        if (draftTags) document.querySelector('.tags-input').value = draftTags;
    }
</script>
{% endblock %} 